import json

from django_redis import get_redis_connection

from utils.cookiesecret import CookieSecret


def merge_cart_cookie_to_redis(request, user, response):
    #获取cookie
    cart_str = request.COOKIES.get('carts')
    # 判断cookie是否为空
    if not cart_str:
        return response
    cart_dict = CookieSecret.loads(cart_str)
    #获取redis
    redis_client = get_redis_connection('carts')

    cart_redis = redis_client.hgetall(user.id)
    cart_redis_dict = {int(sku_id.decode()):json.loads(dict_data.decode()) for sku_id, dict_data in cart_redis.items()}
    #合并
    cart_redis_dict.update(cart_dict)
    # 保存到数据库
    for sku_id in cart_redis_dict:
        redis_client.hset(user.id, sku_id, json.dumps(cart_redis_dict[sku_id]))

    response.delete_cookie('carts')

    return response